package cn.cslg.edu.weather;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.zaaach.citypicker.CityPickerActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.cslg.edu.weather.adapter.WeatherAdapter;
import cn.cslg.edu.weather.bean.WeatherResponse;
import cn.cslg.edu.weather.network.RetrofitHelper;
import cn.cslg.edu.weather.util.HttpUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private List<WeatherResponse.weatherBean> mBeanList;
    private ImageView dataRefresh;
    private RelativeLayout rlCity;
    private TextView aqiText;
    private TextView weatherQualityText;
    private TextView weatherMonitor;
    private TextView mainPollution;
    private TextView locCity;
    private RecyclerView weatherRecycler;
    private ImageView bingPicImg;
    private ProgressDialog progressDialog;

    private static final int REQUEST_CODE_PICK_CITY = 233;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_main);
        initViews();
        showProgressDialog();
        getTestInfo(locCity.getText().toString());
    }

    private void initViews() {
        dataRefresh = findViewById(R.id.refresh_image);
        rlCity = findViewById(R.id.refresh_layout);
        aqiText = findViewById(R.id.aqi_text);
        weatherQualityText = findViewById(R.id.weather_quality);
        mainPollution = findViewById(R.id.pollution_main);
        weatherRecycler = findViewById(R.id.weather_list);
        bingPicImg = findViewById(R.id.bing_pic_img);
        weatherMonitor = findViewById(R.id.weather_monitor);
        locCity = findViewById(R.id.loc_city);

        dataRefresh.setOnClickListener(this);
        rlCity.setOnClickListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        weatherRecycler.setLayoutManager(layoutManager);
        weatherRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String bingPic = prefs.getString("bing_pic", null);
        if (bingPic != null) {
            Glide.with(this).load(bingPic).into(bingPicImg);
        } else {
            loadBingPic();
        }

        SharedPreferences preferences = this.getSharedPreferences("tel",MODE_PRIVATE);
        locCity.setText(preferences.getString("city","常熟"));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.refresh_image:
                showProgressDialog();
                getTestInfo(locCity.getText().toString());
                loadBingPic();
                break;
            case R.id.refresh_layout:
                selectCity();
                break;
                default:
                    break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode ==RESULT_OK) {
            if (data != null) {
                String city = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
                locCity.setText(city);
                showProgressDialog();
                getTestInfo(city);
            }
        }
    }

    private void getTestInfo(String city) {
        RetrofitHelper.getTestService()
                .getTestInfo(city)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<WeatherResponse.weatherBean>>() {
                    @Override
                    public void onCompleted() {
                        aqiText.setText(String.valueOf(mBeanList.get(mBeanList.size() - 1).getAqi()));
                        weatherQualityText.setText(mBeanList.get(mBeanList.size() - 1).getQuality());
                        if (mBeanList.get(mBeanList.size() - 1).getPrimary_pollutant().length() == 0) {
                            mainPollution.setText("今日天气很好，无污染");
                        } else {
                            mainPollution.setText(mBeanList.get(mBeanList.size() - 1).getPrimary_pollutant());
                        }
                        weatherMonitor.setText(mBeanList.get(mBeanList.size() - 1).getTime_point());
                        WeatherAdapter weatherAdapter = new WeatherAdapter(mBeanList);
                        weatherRecycler.setAdapter(weatherAdapter);
                        closeProgressDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<WeatherResponse.weatherBean> weatherBeanList) {
                        mBeanList = weatherBeanList;
                    }
                });

    }

    /**
     * 加载必应每日一图
     */
    private void loadBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
                editor.putString("bing_pic", bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(MainActivity.this).load(bingPic).into(bingPicImg);
                    }
                });
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.developer_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.city_select:
                selectCity();
                break;
            case R.id.about:
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setTitle("关于");
                dialog.setMessage(R.string.about_content);
                dialog.setPositiveButton("确定", null);
                dialog.show();
                break;
                default:
                    break;
        }
        return true;
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog(){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(this);
            progressDialog.setMessage("天气信息获取中，请稍等");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }
    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }

    private void selectCity() {
        startActivityForResult(new Intent(this, CityPickerActivity.class),
                REQUEST_CODE_PICK_CITY);
    }

    @Override
    protected void onStop() {
        super.onStop();
        //获取一个文件名为tel,权限为private的xml文件的SharedPreferences对象
        SharedPreferences preferences = getSharedPreferences("city",MODE_PRIVATE);

        //得到SharePreferences.Editor对象,并保存数据到该对象中
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("cityName",locCity.getText().toString().trim());

        //保存key-value对到文件中
        editor.apply();
    }
}
